/**
 * 初始化车次核销详情对话框
 */
var TTrainInfoDlg = {
    id: "TTrTable",	//表格id
    table: null,
    tTrainInfoData : {},
    lock: false
};


/**
 * 初始化表格的列
 */
var mA=1
var mB=1
var mC=1
var mD=1
var mE=1
var mF=1
TTrainInfoDlg.initColumn = function () {
    return [
        {title: '运单号', field: 'original_num',width: 100, visible: true, align: 'center', valign: 'middle'},
        {title: '货物名称', field: 'goods_name',width: 100, visible: true, align: 'center', valign: 'middle'},
        {title: '收货人', field: 'consignee',width: 100, visible: true, align: 'center', valign: 'middle'},
        {title: '件数', field: 'goods_piece',width: 100, visible: true, align: 'center', valign: 'middle'},
        {title: '送货地址', field: 'receivingAddress',width: 100, visible: true, align: 'center', valign: 'middle'},
        {title: '提付<input type="checkbox" value="" title="月结" lay-filter="aDemo" checked >', field: 'payment', width: 120,visible: true, align: 'center', valign: 'middle'},
        {title: '代收货款<input type="checkbox" value="" title="月结" lay-filter="bDemo" checked>', field: 'collection',width: 150, visible: true, align: 'center', valign: 'middle'},
        {title: '落地费<input type="checkbox" value="" title="月结" lay-filter="fDemo" checked>', field: 'extra_money',width: 150, visible: true, align: 'center', valign: 'middle'},
        {title: '中转费<input type="checkbox" value="" title="月结" lay-filter="cDemo" checked>',event: 'a', field: 'zz',width: 150, visible: true, align: 'center', valign: 'middle'},
        {title: '送货费<input type="checkbox" value="" title="月结" lay-filter="dDemo" checked>',event: 'b', field: 'sh',width: 150, visible: true, align: 'center', valign: 'middle'},
        {title: '搬运费<input type="checkbox" value="" title="月结" lay-filter="eDemo" checked>',event: 'c', field: 'ty',width: 150, visible: true, align: 'center', valign: 'middle'},
        {title: '通知发货', field: 'notice',width: 100, visible: true, align: 'center', valign: 'middle',
        templet: function (d) {
            if(d.notice==1){
                return "是";
            }else {
                return "否";
            }
    }},
        {title: '回单要求', field: 'receipt',width: 100, visible: true, align: 'center', valign: 'middle'}

    ];
};
TTrainInfoDlg.summary = function() {
    alert()
}

/**
 * 清除数据
 */
TTrainInfoDlg.clearData = function() {
    this.tTrainInfoData = {};
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
TTrainInfoDlg.set = function(key, val) {
    this.tTrainInfoData[key] = (typeof val == "undefined") ? $("#" + key).val() : val;
    return this;
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
TTrainInfoDlg.get = function(key) {
    return $("#" + key).val();
}

/**
 * 关闭此对话框
 */
TTrainInfoDlg.close = function() {
    parent.layer.close(window.parent.table1.layerIndex);
}

/**
 * 收集数据
 */
TTrainInfoDlg.collectData = function() {
    this
        .set('ids')
        .set('cash')
        .set('weixin')
        .set('alipay')
        .set('bank')
        .set('driver_name')
        .set('phone')
        .set('car_no')
        .set('temOrderFeeS',JSON.stringify(vDate))
        .set('mA',mA)
        .set('mB',mB)
        .set('mC',mC)
        .set('mD',mD)
        .set('mE',mE)
        .set('mF',mF);
}

/**
 * 提交添加
 */
TTrainInfoDlg.addSubmit = function() {

    this.clearData();
    this.collectData();

    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/tTrain/add", function(data){
        Feng.success("添加成功!");
        window.parent.TTrain.table.refresh();
        TTrainInfoDlg.close();
    },function(data){
        Feng.error("添加失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.tTrainInfoData);
    ajax.start();
}

/**
 * 提交修改
 */
TTrainInfoDlg.editSubmit = function() {

    this.clearData();
    this.collectData();
    var reg = /^\-?[0-9]+\.?[0-9]*$/;
    if (!reg.test($('#cash').val().trim())  ) {
        Feng.error("现金金额不符合规范，请重新输入");
        return false;
    }
    if (!reg.test($('#weixin').val().trim())  ) {
        Feng.error("微信金额不符合规范，请重新输入");
        return false;
    }
    if (!reg.test($('#alipay').val().trim())  ) {
        Feng.error("支付宝金额不符合规范，请重新输入");
        return false;
    }
    if (!reg.test($('#bank').val().trim())  ) {
        Feng.error("银行卡金额不符合规范，请重新输入");
        return false;
    }

    var cash=parseFloat($('#cash').val().trim());
    var weixin=parseFloat($('#weixin').val().trim());
    var alipay=parseFloat($('#alipay').val().trim());
    var bank=parseFloat($('#bank').val().trim());
    var xj=parseFloat($('#sz_money').val().trim());
    if((cash+weixin+alipay+bank)!=xj){
        Feng.error("收支金额不等!");
        return;
    }
    if($('#driverId').val()==''){
        Feng.error("司机不能为空!");
        return;
    }
    if($('#transferId').val()==''){
        Feng.error("中转网点不能为空!");
        return;
    }


   var  w = window.open();
    if(!TTrainInfoDlg.lock) {
        //防止多次点击
        TTrainInfoDlg.lock = true; // 锁定
        //提交信息
        var ajax = new $ax(Feng.ctxPath + "/tTrain/transferUpdate", function (data) {
            Feng.success("修改成功!");
            window.parent.table1.table.refresh();
            window.parent.ids.splice(0, window.parent.ids.length);
            window.parent.removeAll();
            TTrainInfoDlg.close();
            w.location = Feng.ctxPath + "/tOrder/transfer_print/" + data.code
        }, function (data) {
            Feng.error("修改失败!" + data.responseJSON.message + "!");
        });
        ajax.set(this.tTrainInfoData);
        ajax.set("xj", $('#sz_money').val());
        ajax.set("gz", $('#gz_money').val());
        ajax.set("transferId", $('#transferId').val());
        ajax.set("driverId", $('#driverId').val());
        ajax.set("driver_name", $('#driver_name').val());
        ajax.set("transfer_name", $('#transfer_name').val());
        ajax.start();
    }
}
function mUpdata(obj, type,field) {
    var data = obj.data;
    var mTitle ;
    var mValue = 0;
    if (type == 'a') {
        mValue = data.zz;
        mTitle="中转费";
    } else if (type == 'c') {
        mValue = data.ty;
        mTitle="搬运费";
    } else if (type == 'b') {
        mValue = data.sh;
        mTitle="送货费";
    }
    //这里一般是发送修改的Ajax请求

    //同步更新表格和缓存对应的值
    layer.prompt({
        formType: 2
        , title: '修改' + mTitle + '金额'
        , value: mValue
    }, function (value, index) {
        value=value.trim();
        var reg = /^\-?[0-9]+\.?[0-9]*$/;
        if (!reg.test(value)  ) {
            Feng.error("输入数字不规范，请重新输入");
            return false;
        }
        var mSum = 0;
        var fee_id = "";
        if (type == 'a') {
            obj.update({
                zz:value
            });
            obj.data.zz=value;

        } else if (type == 'b') {
           obj.update({
                sh:value
            });
            obj.data.sh=value;
        } else if (type == 'c') {
            obj.update({
                ty:value
            });
            obj.data.ty=value;
        }
        upMdate(obj.data,mSum);
        layer.close(index);


    });
}
function upMdate(oData,oSum) {
    var mSum=0;
    var uSum=0;
    var tf=0;
    var ds=0;
    var zz=0;
    var sh=0;
    var by=0;

    var xj=0;
    var gz=0;
    for(var i=0;i<vDate.length;i++){

        if(this.vDate[i].id==oData.id){
            this.vDate[i]=oData;
        }
        if(mA==0){
            xj=xj+parseFloat(this.vDate[i].payment);
        }else{
            gz=gz+parseFloat(this.vDate[i].payment);
        }
        if(mB==0){
            xj=xj+parseFloat(this.vDate[i].collection);
        }else{
            gz=gz+parseFloat(this.vDate[i].collection);
        }
        if(mC==0){
            xj=xj+parseFloat(this.vDate[i].zz)*-1;
        }else{
            gz=gz+parseFloat(this.vDate[i].zz)*-1;
        }
        if(mD==0){
            xj=xj+parseFloat(this.vDate[i].sh)*-1;
        }else{
            gz=gz+parseFloat(this.vDate[i].sh)*-1;
        }

        if(mE==0){
            xj=xj+parseFloat(vDate[i].ty)*-1;
        }else{
            gz=gz+parseFloat(vDate[i].ty)*-1;
        }

        if(mF==0){
            xj=xj+parseFloat(vDate[i].extra_money);
        }else{
            gz=gz+parseFloat(vDate[i].extra_money);
        }
    }
    $('#all_money').val(xj+gz);
    $('#cash').val(xj);
    $('#sz_money').val(xj);
    $('#gz_money').val(gz);
}

var mDate=null;
var vDate=null;
TTrainInfoDlg.collectSum = function(m) {
    if(m){
        mDate=m;
        this.vDate=m.data;
    }

    var tf=0;
    var ds=0;
    var zz=0;
    var sh=0;
    var by=0;

    var xj=0;
    var gz=0;
    for(var i=0;i<mDate.data.length;i++){
        if(mA==0){
            xj=xj+parseFloat(mDate.data[i].payment);
        }else{
            gz=gz+parseFloat(mDate.data[i].payment);
        }
        if(mB==0){
            xj=xj+parseFloat(mDate.data[i].collection);
        }else{
            gz=gz+parseFloat(mDate.data[i].collection);
        }
        if(mC==0){
            xj=xj+parseFloat(mDate.data[i].zz)*-1;
        }else{
            gz=gz+parseFloat(mDate.data[i].zz)*-1;
        }
        if(mD==0){
            xj=xj+parseFloat(mDate.data[i].sh)*-1;
        }else{
            gz=gz+parseFloat(mDate.data[i].sh)*-1;
        }
        if(mE==0){
            xj=xj+parseFloat(mDate.data[i].ty)*-1;
        }else{
            gz=gz+parseFloat(mDate.data[i].ty)*-1;
        }
        if(mF==0){
            xj=xj+parseFloat(mDate.data[i].extra_money);
        }else{
            gz=gz+parseFloat(mDate.data[i].extra_money);
        }
    }
    $('#all_money').val(xj+gz);
    $('#cash').val(xj);
    $('#sz_money').val(xj);
    $('#gz_money').val(gz);
}

var aTable = null
var mTable = null;
$(function () {
    var defaultColunms = TTrainInfoDlg.initColumn();
    aTable = new LYTable(TTrainInfoDlg.id, "/tOrder/zzDataList?ids="+$('#ids').val(), defaultColunms);
    layui.use('table', function () {
        mTable = layui.table;
        TTrainInfoDlg.table = aTable.initCallBack(mTable,TTrainInfoDlg.collectSum);

        mTable.on('tool(' + TTrainInfoDlg.id + ')', function (obj) {
            mUpdata(obj, obj.event,obj.field);
        })
        var form = layui.form;
        form.on('checkbox(aDemo)', function(obj){
            if(obj.elem.checked){
                mA=1;
            }else{
                mA=0;
            }
            TTrainInfoDlg.collectSum();
        });
        form.on('checkbox(bDemo)', function(obj){
            if(obj.elem.checked){
                mB=1;
            }else{
                mB=0;
            }
            TTrainInfoDlg.collectSum();
        });
        form.on('checkbox(cDemo)', function(obj){
            if(obj.elem.checked){
                mC=1;
            }else{
                mC=0;
            }
            TTrainInfoDlg.collectSum();
        });
        form.on('checkbox(dDemo)', function(obj){
            if(obj.elem.checked){
                mD=1;
            }else{
                mD=0;
            }
            TTrainInfoDlg.collectSum();
        });
        form.on('checkbox(eDemo)', function(obj){
            if(obj.elem.checked){
                mE=1;
            }else{
                mE=0;
            }
            TTrainInfoDlg.collectSum();
        });
        form.on('checkbox(fDemo)', function(obj){
            if(obj.elem.checked){
                mF=1;
            }else{
                mF=0;
            }
            TTrainInfoDlg.collectSum();
        });
    })

    $("#driver_name").bsSuggest('init', {
        /*url: "/rest/sys/getuserlist?keyword=",
        searchFields: [ "shortAccount"],*/
        effectiveFieldsAlias:{driver_name: "司机"},
        effectiveFields: ["id", "driver_name"],
        clearable: true,
        url: Feng.ctxPath + "/tOrder/searchList",
        idField: "id",
        keyField: "driver_name"
    }).on('onDataRequestSuccess', function (e, result) {
        console.log('onDataRequestSuccess: ', result);
        a=result.value;
    }).on('onSetSelectValue', function (e, keyword, data) {
        console.log('onSetSelectValue: ', keyword, e);
        // for(var i=0;i<a.length;i++){
        //     console.log('onSetSelectValue: ',a[i].id);
        // if(a[i].id==keyword.id){
        //     $('#phone').val(a[i].phone);
        //     $('#car_no').val(a[i].car_no);
            $('#driverId').val(keyword.id);

        // }
        // }
    }).on('onUnsetSelectValue', function () {
        console.log('onUnsetSelectValue');
        $('#driverId').val('');
    });


    $("#transfer_name").bsSuggest('init', {
        /*url: "/rest/sys/getuserlist?keyword=",
        searchFields: [ "shortAccount"],*/
        effectiveFieldsAlias:{dotName: "网点名称"},
        effectiveFields: ["id", "dotName"],
        clearable: true,
        url: Feng.ctxPath + "/tOrder/searchDotList",
        idField: "id",
        keyField: "dotName"
    }).on('onDataRequestSuccess', function (e, result) {
        console.log('onDataRequestSuccess: ', result);
        a=result.value;
    }).on('onSetSelectValue', function (e, keyword, data) {
        console.log('onSetSelectValue: ', keyword, e);
        $('#transferId').val(keyword.id);
    }).on('onUnsetSelectValue', function () {
        console.log('onUnsetSelectValue');
        $('#transferId').val('');
    });

});
